# -*- coding: utf-8 -*-  
from PIL import Image
import pytesseract
import os
import cv2
import  numpy as np
import matplotlib.pyplot as plt 

adb_path = 'D:\\android\\android-sdk\\platform-tools\\adb'

def ImageToText(image, lang ='chi_sim' ):
    """
    文字识别
    """
    return pytesseract.image_to_string(Image.open(image),lang=lang)

def screensize():
    """
    adb shell dumpsys window displays |head -n 3
    """
    return adb('shell dumpsys window displays')

def adb(cmd):
    """
    命令执行
    """
    print(('%s %s' % (adb_path, cmd)))
    return os.popen('%s %s' % (adb_path, cmd)).read()

def back():
    """
    返回上一级
    adb shell input keyevent 4 
    """
    return adb('shell input keyevent 4 ')

def swipe(start_x,start_y, end_x, end_y, times = 100):
    """
    在终端中输入adb shell input swipe 540 1300 540 500 100   从坐标点（540，1300）用100ms滑动到（540，500）坐标点。
    最后这个100时间以毫秒为单位，可以不填则为默认时间。
    """
    return adb('shell input swipe %s %s %s %s %s' % (start_x,start_y, end_x, end_y, times))

def screencap(image_name = 'screenshot.png', download = 'e:/'):
    """
    屏幕截图
    """
    adb('shell /system/bin/screencap -p /sdcard/%s' % image_name)
    adb('pull /sdcard/%s %s' % (image_name, download + image_name))

def touch(touch_x, touch_y):
    return adb('shell input tap %s %s' % (touch_x, touch_y))
    
def ResizeImage(image_path,start_x = 844.577,start_y = 219.76,end_x = 1026.39,end_y = 396.383):
    """
    图片裁剪
    """
    from PIL import Image
 
    img = Image.open(image_path)
    box1 = (start_x, start_y, end_x, end_y)
    image1 = img.crop(box1)
    image1.save('resize_'+image_path.split("/")[-1])

def circle(image):
    """
    选中图片中的圆形图案
    """
    import cv2 
    import numpy as np 
    import matplotlib.pyplot as plt 
  
    img = cv2.imread(image) 
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) 
  
    plt.subplot(121),plt.imshow(gray,'gray') 
    plt.xticks([]),plt.yticks([]) 
    circles1 = cv2.HoughCircles(gray,cv2.HOUGH_GRADIENT,1, 
    600,param1=100,param2=30,minRadius=80,maxRadius=97) 
    circles = circles1[0,:,:] 
    circles = np.uint16(np.around(circles)) 
    for i in circles[:]:  
        cv2.circle(img,(i[0],i[1]),i[2],(255,0,0),5) 
        cv2.circle(img,(i[0],i[1]),2,(255,0,255),10) 
        cv2.rectangle(img,(i[0]-i[2],i[1]+i[2]),(i[0]+i[2],i[1]-i[2]),(255,255,0),5) 

    if(i[0] and i[1]):
        return True
#    plt.subplot(122),plt.imshow(img) 
#    plt.xticks([]),plt.yticks([]) 
#    plt.show()
    


#均值哈希算法
def aHash(img):

    #缩放为8*8
    img=cv2.resize(img,(8,8),interpolation=cv2.INTER_CUBIC)
    #转换为灰度图
    gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    #s为像素和初值为0，hash_str为hash值初值为''
    s=0
    hash_str=''
    #遍历累加求像素和
    for i in range(8):
        for j in range(8):
            s=s+gray[i,j]
    #求平均灰度
    avg=s/64
    #灰度大于平均值为1相反为0生成图片的hash值
    for i in range(8):
        for j in range(8):
            if  gray[i,j]>avg:
                hash_str=hash_str+'1'
            else:
                hash_str=hash_str+'0'            
    return hash_str

#差值感知算法
def dHash(img):
    #缩放8*8
    img=cv2.resize(img,(9,8),interpolation=cv2.INTER_CUBIC)
    #转换灰度图
    gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    plt.imshow(gray,'gray') 
    plt.show()
    hash_str=''
    #每行前一个像素大于后一个像素为1，相反为0，生成哈希
    for i in range(8):
        for j in range(8):
            if   gray[i,j]>gray[i,j+1]:
                hash_str=hash_str+'1'
            else:
                hash_str=hash_str+'0'
    return hash_str

#Hash值对比
def cmpHash(hash1,hash2):
    n=0
    #hash长度不同则返回-1代表传参出错
    if len(hash1)!=len(hash2):
        return -1
    #遍历判断
    for i in range(len(hash1)):
        #不相等则n计数+1，n最终为相似度
        if hash1[i]!=hash2[i]:
            n=n+1
    return n


